package com.dstats.sync;

import android.content.Context;
import android.os.AsyncTask;

import com.dstats.network.JsonReader;
import com.dstats.network.WebApiClientListener;

/**
 * Created by Nicholas M. Mizoguchi on 8/29/14.
 */
public abstract class SyncAbstractModel implements WebApiClientListener {

    public static final int SYNC_FAIL_EXC = 5431;
    public static final int SYNC_SERVER_ERROR = -1;
    public static final int REQUEST_FINISHED = 38440;
    private final Context mContext;

    public SyncAbstractModel(Context context) {
        this.mContext = context;
    }

    public void pull() {
        onPull();
    }

    public void push() {
        onPush();
    }

    protected abstract void onPull();

    protected abstract void onPush();

    public void onPullFinish(JsonReader response, Object result) {

    }

    protected Context getContext() {
        return mContext;
    }

    protected abstract ResultHolder saveResponse(JsonReader response);

    @Override
    public void onResponse(JsonReader response) {
        new AsyncTask<JsonReader, Integer, ResultHolder>() {

            @Override
            protected ResultHolder doInBackground(JsonReader... jsonReaders) {
                return saveResponse(jsonReaders[0]);
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, response);
        onPullFinish(response, 0);
    }

    @Override
    public void onException(Exception exc) {
        exc.printStackTrace();
    }

    protected class ResultHolder {
        JsonReader response;
        Object result;

        public ResultHolder(JsonReader response, Object result) {
            this.response = response;
            this.result = result;
        }
    }

}
